package com.ruoyi.web.controller.system;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 库存 信息操作处理
 * 
 * @author ruoyi
 * @date 2019-04-19
 */
@Controller
@RequestMapping("/system/tInventory")
public class TInventoryController extends BaseController
{
    private String prefix = "system/tInventory";
	
	@Autowired
	private ITInventoryService tInventoryService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ITSaleService saleService;
	@Autowired
	private ITStocktakingService stocktakingService;
	@Autowired
	private ITypeService typeService;
	@Autowired
	private ITRecorService recorService;
	
	@RequiresPermissions("system:tInventory:view")
	@GetMapping()
	public String tInventory(ModelMap mmap)
	{
		if(!String.valueOf(ShiroUtils.getSysUser().getDeptId()).equals("100")){
			mmap.put("deptId",ShiroUtils.getSysUser().getDeptId());
		}
	    return prefix + "/tInventory";
	}
	
	/**
	 * 查询库存列表
	 */
	@RequiresPermissions("system:tInventory:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(TInventory tInventory)
	{
		startPage();
        List<TInventory> list = tInventoryService.selectTInventoryList(tInventory);
		return getDataTable(list);
	}
	
	
	/**
	 * 导出库存列表
	 */
//	@RequiresPermissions("system:tInventory:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TInventory tInventory)
    {
		tInventory.setIssale("0");
    	List<TInventory> list = tInventoryService.selectTInventoryList(tInventory);
        ExcelUtil<TInventory> util = new ExcelUtil<TInventory>(TInventory.class);
        return util.exportExcel(list, "商品数据");
    }
	
	/**
	 * 新增库存
	 */
	@GetMapping("/add")
	public String add(ModelMap mmap) {
		Type type = new Type();
		type.setParentId(Long.valueOf(100));
		List<Type> category = typeService.selectTypeList(type);
		mmap.put("category", category);

		//获取品类品种的操作记录
		TRecor tRecor= recorService.selectTRecorById(ShiroUtils.getUserId());
		mmap.put("tRecor", tRecor == null ? new TRecor():tRecor);

		if(!String.valueOf(ShiroUtils.getSysUser().getDeptId()).equals("100")){
			mmap.put("deptId",ShiroUtils.getSysUser().getDeptId());
			mmap.put("deptName",ShiroUtils.getSysUser().getDept().getDeptName());
		}


		return prefix + "/add";
	}
	
	/**
	 * 新增保存库存
	 */
	@RequiresPermissions("system:tInventory:add")
	@Log(title = "库存", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(TInventory tInventory)
	{
		//保存品类品种操作记录

		TRecor tRecor = recorService.selectTRecorById(ShiroUtils.getUserId());
		if(tRecor != null){
			tRecor.setCategory(tInventory.getCategory());
			tRecor.setVariety(tInventory.getVariety());
			recorService.updateTRecor(tRecor);
		}else{
			TRecor t = new TRecor();
			t.setUserId(ShiroUtils.getUserId());
			t.setCategory(tInventory.getCategory());
			t.setVariety(tInventory.getVariety());
			recorService.insertTRecor(t);
		}

		tInventory.setRegistrant(ShiroUtils.getSysUser().getUserName());
		tInventory.setIndate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		return toAjax(tInventoryService.insertTInventory(tInventory));
	}

	/**
	 * 修改库存
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Long id, ModelMap mmap)
	{
		Type type = new Type();
		type.setParentId(Long.valueOf(100));
		List<Type> category = typeService.selectTypeList(type);
		mmap.put("category", category);

		TInventory tInventory = tInventoryService.selectTInventoryById(id);
		mmap.put("tInventory", tInventory);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存库存
	 */
	@RequiresPermissions("system:tInventory:edit")
	@Log(title = "库存", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(TInventory tInventory)
	{		
		return toAjax(tInventoryService.updateTInventory(tInventory));
	}

	/**销售*/
	@GetMapping("/sale/{id}")
	public String sale(@PathVariable("id") Long id, ModelMap mmap) {
		TInventory tInventory = tInventoryService.selectTInventoryById(id);
		mmap.put("tInventory", tInventory);
		SysUser sysUser = new SysUser();
		sysUser.setDeptId(ShiroUtils.getSysUser().getDeptId());
		List<SysUser> sysUsers = sysUserService.selectUserList(sysUser);
		mmap.put("sysUsers", sysUsers);

		Type type = new Type();
		type.setParentId(Long.valueOf(0));
		List<Type> category = typeService.selectTypeList(type);
		mmap.put("category", category);

		return prefix + "/sale";
	}

	/**销售保存*/
	@PostMapping("/sale")
	@ResponseBody
	public AjaxResult sale(TSale tSale) {

		//将商品设置为已销售
		Long inventoryId = tSale.getInventory();
		TInventory tInventory = tInventoryService.selectTInventoryById(inventoryId);
		tInventory.setId(inventoryId);
		tInventory.setIssale("1");
		tInventoryService.updateTInventory(tInventory);
		if(!tSale.getLabelprice().equals(new BigDecimal(0))){
			tSale.setDiscount(tSale.getSaleprice().divide(tSale.getLabelprice(),2).divide(new BigDecimal(100))+"%");
		}else{
			tSale.setDiscount("0");
		}
		tSale.setRegistrant(ShiroUtils.getSysUser().getUserName());
		tSale.setSaledate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		return toAjax(saleService.insertTSale(tSale));
	}

	/**盘点*/
	@GetMapping("/stocktaking/{id}")
	public String stocktaking(@PathVariable("id") Long id, ModelMap mmap) {
		TInventory tInventory = tInventoryService.selectTInventoryById(id);
		mmap.put("tInventory", tInventory);

		Type type = new Type();
		type.setParentId(Long.valueOf(0));
		List<Type> category = typeService.selectTypeList(type);
		mmap.put("category", category);

		return prefix + "/stocktaking";
	}


	@GetMapping("/queryDataByCode/{barcode}")
	@ResponseBody
	public AjaxResult getLevel2(@PathVariable("barcode") String barcode) {
		TInventory parm = new TInventory();
		Map<String,Object> map = new HashMap<>();
		map.put("barcode2",barcode);
		parm.setParams(map);
		List<TInventory> list = tInventoryService.selectTInventoryList(parm);
		AjaxResult ajaxResult = new AjaxResult();
		ajaxResult.put("data",list);
		return ajaxResult;
	}


	/**
	 * 校验code
	 */
	@PostMapping("/checkBarcodeUnique")
	@ResponseBody
	public String checkBarcodeUnique(TInventory tInventory)
	{
		List<TInventory> list = tInventoryService.selectTInventoryByCode(tInventory.getBarcode());
		if(list.size() > 0){
			return UserConstants.DEPT_NAME_NOT_UNIQUE;
		}else{
			return UserConstants.DEPT_NAME_UNIQUE;
		}
	}


	/**盘点保存*/
	@PostMapping("/stocktaking")
	@ResponseBody
	public AjaxResult stocktaking(TStocktaking tStocktaking) {

		//将商品设置为已盘点
		Long inventoryId = tStocktaking.getInventory();
		TInventory tInventory = tInventoryService.selectTInventoryById(inventoryId);
		tInventory.setId(inventoryId);
		tInventory.setIsstocktaking("1");
		tInventoryService.updateTInventory(tInventory);

		tStocktaking.setReckoningdate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		tStocktaking.setReckoningman(ShiroUtils.getSysUser().getUserName());
		tStocktaking.setRegistrant(ShiroUtils.getSysUser().getUserName());
		return toAjax(stocktakingService.insertTStocktaking(tStocktaking));
	}
	
	/**
	 * 删除库存
	 */
	@RequiresPermissions("system:tInventory:remove")
	@Log(title = "库存", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(tInventoryService.deleteTInventoryByIds(ids));
	}
	
}
